let util = {}

/**
 * 判断数据类型
 * @param n
 * @returns {string}
 */
util.varType = (n) =>{
	let typeStr = Object.prototype.toString.call(n)
	let typeName = ''
	switch(typeStr){
		case '[object String]':
			typeName = 'string'
			break
		case '[object Number]':
			typeName = 'number'
			break
		case '[object Boolean]':
			typeName = 'boolean'
			break
		case '[object Undefined]':
			typeName = 'undefined'
			break
		case '[object Object]':
			typeName = 'object'
			break
		case '[object Array]':
			typeName = 'array'
			break
		case '[object Null]':
			typeName = 'null'
			break
		case '[object RegExp]':
			typeName = 'RegExp'
			break
		case '[object Symbol]':
			typeName = 'symbol'
			break
		case '[object JSON]':
			typeName = 'json'
			break
		case '[object Math]':
			typeName = 'math'
			break
		case '[object Date]':
			typeName = 'Date'
			break
		default:
			typeName = 'object'
	}
	return typeName
}

/**
 * 日期格式化
 * @param n
 * @returns {string}
 */
util.formatDate = (date,fmt) =>{
	if(util.varType(date) !== 'Date'){
		if(util.varType(date) === 'string'){
			date = date.replace(/-/g,'/')
		}
		date = new Date(date)
	}
	let padLeftZero = (str) =>{
		return ('00' + str).substr(str.length)
	}
	if(/(y+)/.test(fmt)){
		fmt = fmt.replace(RegExp.$1,(date.getFullYear() + '').substr(4 - RegExp.$1.length))
	}
	let o = {
		'M+':date.getMonth() + 1,
		'd+':date.getDate(),
		'h+':date.getHours(),
		'm+':date.getMinutes(),
		's+':date.getSeconds()
	}
	for(let k in o){
		if(new RegExp(`(${k})`).test(fmt)){
			let str = o[k] + ''
			fmt = fmt.replace(RegExp.$1,RegExp.$1.length === 1?str:padLeftZero(str))
		}
	}
	return fmt
}

/**
 * 到店时间计算
 */
util.calculateTime = (startTime,timeLong) =>{
	if(util.varType(startTime) !== 'Date'){
		if(util.varType(startTime) === 'string'){
			startTime = startTime.replace(/-/g,'/')
		}
		startTime = new Date(startTime).getTime()
	}
	timeLong = timeLong * 60 * 1000
	startTime += timeLong
	return util.formatDate(startTime,'yyyy-MM-dd hh:mm:ss')
}

/**
 * 获取url参数
 */
util.getQueryString = (name) =>{
	let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	let r = window.location.search.substr(1).match(reg);
	if(r != null) return decodeURI(r[2]);
	return null;
}

/**
 * 数组排序
 */
util.compare = (prop) =>{
	return function(obj1,obj2){
		let val1 = obj1[prop];
		let val2 = obj2[prop];
		if(val1 < val2){
			return - 1;
		}else if(val1 > val2){
			return 1;
		}else{
			return 0;
		}
	}
}

/**
 * 二分法排序
 * @param arr
 * @returns {*}
 */
util.twoSort = (arr) =>{
//最后当数组长度只有一的时候，不再往下执行
	if(arr.length <= 1){
		return arr;
	}
	let middle = arr.splice(Math.floor(arr.length / 2),1);
	let leftArr = [];
	let rightArr = [];
	for(let i = 0; i < arr.length; i ++){
		if(parseInt(arr[i]) <= middle){
			leftArr.push(arr[i]);       //把比中间值小的放一个数组
		}else{
			rightArr.push(arr[i]);      //把比中间值大的放另一个数组
		}
	}
	//concat() 方法用于连接两个或多个数组。
	//再对小数组继续回调上面的分组方法
	return util.twoSort(leftArr).concat(middle,util.twoSort(rightArr));
}

/**
 * 对象数组二分法排序
 * @param arr
 * @returns {*}
 */
util.sortForObjArray = (arr,prop) =>{
	if(arr.length <= 1){
		return arr
	}
	arr = util.deepClone(arr)
	let propArr = []
	let resultArr = []
	for(let item of arr){
		let propVal = eval('item.' + prop)
		if(! ! propVal){
			propArr.push(propVal)
		}
	}
	if(propArr.length > 0){
		propArr = util.twoSort(propArr)
	}else{
		return arr
	}
	for(let propItem of propArr){
		for(let arrItem of arr){
			let arrVal = eval('arrItem.' + prop)
			if(propItem == arrVal && resultArr.every(value => value != arrItem)){
				resultArr.push(arrItem)
				break
			}
		}
	}
	return resultArr
}

/**
 * 微信支付
 */
util.weChatPay = (params) =>{
	return new Promise((resolve,reject) =>{
		if(typeof WeixinJSBridge == undefined){
			if(document.addEventListener){
				document.addEventListener('WeixinJSBridgeReady',onBridgeReady,false);
			}else if(document.attachEvent){
				document.attachEvent('WeixinJSBridgeReady',onBridgeReady);
				document.attachEvent('onWeixinJSBridgeReady',onBridgeReady);
			}
		}else{
			WeixinJSBridge.invoke('getBrandWCPayRequest',params,(res) =>{
				if(res.err_msg == "get_brand_wcpay_request:ok"){
					resolve(res)
				}else if(res.err_msg == "get_brand_wcpay_request:cancel"){
					reject('支付已取消')
				}else if(res.err_msg == "get_brand_wcpay_request:fail"){
					reject('支付失败')
				}else{
					reject('微信SDK不存在')
				}
			})
		}
	})
}

/**
 * 小于10 补全
 * @param n
 * @returns {string}
 */
const num = (n) =>{
	return n < 10?'0' + n:'' + n
}

/**
 * 时分秒倒计时
 */
util.countdown = (value) =>{
	if(util.varType(value) !== 'Date'){
		value = new Date(value).getTime()
	}
	let maxTime = value - new Date().getTime()
	let second,hour,minute
	second = Math.floor((maxTime / 1000) % 60)       //计算秒
	minute = Math.floor((maxTime / 1000 / 60) % 60) //计算分
	hour = Math.floor(maxTime / 1000 / 3600 / 24) //计算小时
	return num(hour) + ':' + num(minute) + ':' + num(second)
}

/**
 * 天数倒计时
 */
util.countdownDay = (value) =>{
	if(util.varType(value) !== 'Date'){
		value = new Date(value).getTime()
	}
	let maxTime = value - new Date().getTime()
	let day = Math.ceil(maxTime / (1000*60 * 60 * 24))
	return day
}

/**
 * 时分秒倒计时
 */
util.countdownForSecond = (value) =>{
	let day,hour,minute,second
	if(value > 0){ //转换时间
		day = Math.floor(value / (60 * 60 * 24))
		hour = Math.floor(value / (60 * 60)) - (day * 24)
		minute = Math.floor(value / 60) - (day * 24 * 60) - (hour * 60)
		second = Math.floor(value) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
		return num(hour) + ':' + num(minute) + ':' + num(second)
	}
}

/**
 * 订单号生成
 */
util.getOrderNo = () =>{
	return util.formatDate(new Date(),'yyyyMMddhhmmss') + Math.ceil(Math.random() * (9999 - 1000) + 1000)
}

/**
 * 模糊搜索
 */
util.likeFind = (str1,str2) =>{
	var result = str2.indexOf(str1);
	if(result != - 1){
		return true;
	}else{
		return false;
	}
	return false;
}

/**
 * 判断访问终端
 */
util.browser = {
	versions:function(){
		let u = navigator.userAgent,app = navigator.appVersion;
		return {
			trident:u.indexOf('Trident') > - 1, //IE内核
			presto:u.indexOf('Presto') > - 1, //opera内核
			webKit:u.indexOf('AppleWebKit') > - 1, //苹果、谷歌内核
			gecko:u.indexOf('Gecko') > - 1 && u.indexOf('KHTML') == - 1,//火狐内核
			mobile:! ! u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
			ios:! ! u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
			android:u.indexOf('Android') > - 1 || u.indexOf('Linux') > - 1, //android终端或者uc浏览器
			iPhone:u.indexOf('iPhone') > - 1, //是否为iPhone或者QQHD浏览器
			iPad:u.indexOf('iPad') > - 1, //是否iPad
			webApp:u.indexOf('Safari') == - 1 //是否web应该程序，没有头部与底部
		};
	}(),
	language:(navigator.browserLanguage || navigator.language).toLowerCase()
}

/**
 * 导入微信SDK
 */
util.getWXSdk = () =>{
	return new Promise((resolve,reject) =>{
		
	})
}

/**
 * 深拷贝
 */
util.deepClone = (source) =>{
	if(! source || typeof source !== 'object'){
		throw new Error('error arguments','shallowClone');
	}
	var targetObj = source.constructor === Array?[]:{};
	for(var keys in source){
		if(source.hasOwnProperty(keys)){
			if(source[keys] && typeof source[keys] === 'object'){
				targetObj[keys] = source[keys].constructor === Array?[]:{};
				targetObj[keys] = util.deepClone(source[keys]);
			}else{
				targetObj[keys] = source[keys];
			}
		}
	}
	return targetObj;
}

export default util
